package com.gwcm.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gwcm.constant.SaleItemStatusConstants;
import com.gwcm.constant.SaleStatusConstants;
import com.gwcm.exception.BusinessException;
import com.gwcm.mapper.CategoryMapper;
import com.gwcm.mapper.MemberCardMapper;
import com.gwcm.mapper.ProductMapper;
import com.gwcm.mapper.SaleItemMapper;
import com.gwcm.mapper.SaleMapper;
import com.gwcm.model.dto.orderInfo.PosSaleOrderQueryRequest;
import com.gwcm.model.entity.*;
import com.gwcm.model.vo.OrderInfoVo;
import com.gwcm.model.vo.PosSaleOrderVo;
import com.gwcm.model.vo.SaleCategoryByMonthVo;
import com.gwcm.model.vo.SaleItemVo;
import com.gwcm.model.vo.SaleStatisticalByMonthVo;
import com.gwcm.service.ISaleService;
import com.gwcm.service.OrderInfoService;
import com.gwcm.util.PageUtil;
import com.gwcm.util.SnowFlakeUtil;
import com.yhz.commonutil.common.ErrorCode;
import com.yhz.commonutil.constant.SortConstant;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SaleServiceImpl implements ISaleService {
    private Sale currentSale;
    @Resource
    private SaleMapper saleMapper;
    @Resource
    private SaleItemMapper saleItemMapper;
    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private OrderInfoService orderInfoService;

    /**
     * 开始新的销售
     * @return currentSale对象
     */
    @Override
    public Sale makeNewSale() {
        currentSale = new Sale();
        Date saleDate = new Date();
        currentSale.setSaleTime(saleDate);
        String saleNo = "so-" + SnowFlakeUtil.getSnowFlakeId();
        currentSale.setSaleNo(saleNo);
        System.out.println(saleNo);
        currentSale.setStatus(SaleStatusConstants.ORDER_RESERVED);
        return currentSale;
    }

    /**
     * 实例化SaleItem
     * @param product 商品对象
     * @param quantity 数量
     */
    @Override
    public void makeLineItem(Product product, int quantity) {
        // 判断商品是否已在currentSale中有录入记录
        if (!isEntered(product.getProductSn(),quantity)){
            SaleItem saleItem = new SaleItem();
            saleItem.setProductId(product.getId());
            saleItem.setProduct(product);
            saleItem.setPrice(product.getPrice());
            if(product.getStock()-quantity>=0){
                saleItem.setQuantity(quantity);
            }else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
            currentSale.getSaleItems().add(saleItem);
        }
    }

    /**
     * 判断商品是否已录入
     * @param itemSn 产品编号
     * @param quantity 数量
     * @return 布尔结果
     */
    private boolean isEntered(String itemSn, int quantity) {
        boolean flag = false;
        for(SaleItem si : currentSale.getSaleItems()){
            //如果已经录入则修改数量
            if(itemSn.equals(si.getProduct().getProductSn()) && si.getProduct().getStock()-si.getQuantity()>=0){
                flag = true;
                int quantityOriginal = si.getQuantity();
                si.setQuantity(quantityOriginal + quantity);
            }
        }
        return flag;
    }

    /**
     * 结束订单时商品录入
     * @return 总金额
     */
    @Override
    public BigDecimal endSale() {
        BigDecimal total = this.getTotal();
        currentSale.setTotal(total);
        currentSale.setStatus(SaleStatusConstants.ORDER_RESERVED);
        currentSale.setCreateTime(new Date());
        saleMapper.insertSale(currentSale);
        //将订单中商品持久化
        this.insertSaleItemOfCurrentSale(currentSale);
        return total;
    }

    /**
     * 计算总金额
     * @return 总金额
     */
    private BigDecimal getTotal() {
        BigDecimal total = new BigDecimal(0);
        List<SaleItem> saleItemList = currentSale.getSaleItems();
        for(SaleItem si : saleItemList) {
            total = total.add(this.getSubTotal(si));
        }
        System.out.println("我是getTotal的total："+total);
        return total;
    }

    /**
     * 计算小计
     * @param saleItem
     * @return
     */
    public BigDecimal getSubTotal(SaleItem saleItem){
        return saleItem.getPrice().multiply(new BigDecimal(saleItem.getQuantity()));
    }

    /**
     * 订单支付
     * @param cashTendered 付款金额
     * @return 找零
     */
    @Override
    public BigDecimal makePayment(BigDecimal cashTendered) {
        BigDecimal total = currentSale.getTotal();
        Payment payment = new Payment();
        payment.setAmount(total);
        payment.setPayTime(new Date());
        currentSale.setPayment(payment);
        currentSale.setStatus(SaleStatusConstants.ORDER_PAID);
        currentSale.setUpdateTime(new Date());
        //change为找零
        BigDecimal change = cashTendered.subtract(total);
        if (change.compareTo(BigDecimal.ZERO) < 0){
            throw new BusinessException(ErrorCode.SAVE_ERROR);
        }
        saleMapper.updateSale(currentSale);
        //更新订单商品明细的状态和更新时间
        this.updateSaleItemsOfCurrentSaleForMakePayment(currentSale);
        List<SaleItemVo> saleItemVoList = orderInfoService.selectSaleItemBySaleId(currentSale.getSaleId());
        for(SaleItemVo si : saleItemVoList){
            Product product = productMapper.getProductBySn(si.getItemSn());
            product.setStock(product.getStock()-si.getQuantity());
            productMapper.updateProduct(product);
        }
        return change;
    }

    /**
     * 将Sale中的saleItem存入数据库
     * @param currentSale 当前sale对象
     */
    private void insertSaleItemOfCurrentSale(Sale currentSale){
        List<SaleItem> saleItemList = currentSale.getSaleItems();
        for(SaleItem si : saleItemList){
            si.setStatus(SaleItemStatusConstants.ITEM_RESERVED);
            si.setDelFlag("0");
            si.setCreateTime(new Date());
            //注意sale插入db自增生成id后才能getSaleId()取到id值
            si.setSaleId(currentSale.getSaleId());
        }
        saleMapper.batchInsertSaleItemOfCurrentSale(saleItemList);
    }

    private void updateSaleItemsOfCurrentSaleForMakePayment(Sale currentSale){
        SaleItem param = new SaleItem();
        param.setSaleId(currentSale.getSaleId());
        List<SaleItem> saleItems = saleItemMapper.selectSaleItemList(param);
        for (SaleItem si : saleItems){
            si.setStatus(SaleItemStatusConstants.ITEM_PAID);
            si.setUpdateTime(new Date());
            saleItemMapper.updateSaleItem(si);
        }
    }

    /**
     * 修改订单明细数量
     * @param itemSn
     * @param quantity
     */
    @Override
    public void changeQuantityOfSaleItem(String itemSn, int quantity){
        List<SaleItem> saleItems = currentSale.getSaleItems();
        for(SaleItem si : saleItems){
            if(itemSn.equals(si.getProduct().getProductSn()) && si.getProduct().getStock()-si.getQuantity()>=0){
                si.setQuantity(quantity);
            }else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }
    }

    /**
     * 删除订单明细
     * @param itemSn
     */
    @Override
    public void deleteSaleItem(String itemSn){
        List<SaleItem> saleItems = currentSale.getSaleItems();
        Iterator<SaleItem> iterator = saleItems.iterator();
        while (iterator.hasNext()){
            SaleItem si = iterator.next();
            if (itemSn.equals(si.getProduct().getProductSn())){
                iterator.remove();
            }
        }
    }

    @Override
    public SaleStatisticalByMonthVo statisticalByMonth(String year) {
        List<SaleItem> saleItemList=saleItemMapper.listByYear(year);
        saleItemList = saleItemList.stream().filter(saleItem -> "已付款".equals(saleItem.getStatus())).collect(Collectors.toList());
        SaleStatisticalByMonthVo saleStatisticalByMonthVo = new SaleStatisticalByMonthVo();
        int[] saleQuantity = saleStatisticalByMonthVo.getSaleQuantity();
        int[] saleMoney = saleStatisticalByMonthVo.getSaleMoney();

        Map<String, SaleCategoryByMonthVo> saleCategoryByMonthVoMap = new HashMap<>();
        saleItemList.forEach(item->{
            Calendar cal = Calendar.getInstance();
            int quantity = item.getQuantity();
            Long productId = item.getProductId();
            BigDecimal price = item.getPrice();
            cal.setTime(item.getCreateTime());
            int month = cal.get(Calendar.MONTH);
            System.out.println("month:"+month);
            int totalMoney = price.multiply(BigDecimal.valueOf(quantity)).intValue();
            saleQuantity[month] += quantity;
            saleMoney[month] += totalMoney;

            Category category=categoryMapper.selectByProductId(productId);
            SaleCategoryByMonthVo saleCategoryByMonthVo = saleCategoryByMonthVoMap.getOrDefault(category.getCategoryName(), new SaleCategoryByMonthVo());
            if (saleCategoryByMonthVo.getCategoryName() == null) {
                saleCategoryByMonthVo.setCategoryName(category.getCategoryName());
            }
            int[] categorySaleMoney = saleCategoryByMonthVo.getSaleMoney();
            int[] categorySaleQuantity = saleCategoryByMonthVo.getSaleQuantity();
            categorySaleQuantity[month]+=quantity;
            categorySaleMoney[month] += totalMoney;
            saleCategoryByMonthVo.setSaleQuantity(categorySaleQuantity);
            saleCategoryByMonthVo.setSaleMoney(categorySaleMoney);
            saleCategoryByMonthVoMap.put(category.getCategoryName(), saleCategoryByMonthVo);
        });
        saleStatisticalByMonthVo.setSaleCategoryByMonthVoList(saleCategoryByMonthVoMap.values());
        return saleStatisticalByMonthVo;
    }
}
